package com.example.onlinemallsystem.service.impl;

import com.example.onlinemallsystem.entity.Cart;
import com.example.onlinemallsystem.entity.Product;
import com.example.onlinemallsystem.mapper.CartMapper;
import com.example.onlinemallsystem.mapper.ProductMapper;
import com.example.onlinemallsystem.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 购物车服务实现类
 * 实现购物车相关的业务逻辑
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Long addToCart(Long userId, Long productId, Integer quantity) throws RuntimeException {
        if (userId == null || productId == null || quantity == null || quantity <= 0) {
            throw new RuntimeException("参数错误，请检查商品信息");
        }

        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }

        if (product.getStock() < quantity) {
            throw new RuntimeException("商品库存不足");
        }

        Cart existCartItem = cartMapper.getCartItemByUserAndProduct(userId, productId);
        if (existCartItem != null) {
            Integer newQuantity = existCartItem.getQuantity() + quantity;
            if (newQuantity > product.getStock()) {
                throw new RuntimeException("库存不足，无法添加");
            }
            existCartItem.setQuantity(newQuantity);
            cartMapper.updateCartItem(existCartItem);
            return existCartItem.getId();
        } else {
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setProductId(productId);
            cart.setProductName(product.getName());
            cart.setProductPrice(product.getPrice());
            cart.setProductImage(product.getImage());
            cart.setQuantity(quantity);
            cart.setSelected(1);
            cart.setDeleted(0);

            cartMapper.addToCart(cart);
            return cart.getId();
        }
    }

    @Override
    public boolean updateQuantity(Long userId, Long productId, Integer quantity) throws RuntimeException {
        if (userId == null || productId == null || quantity == null || quantity <= 0) {
            throw new RuntimeException("参数错误，请检查");
        }

        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }

        if (quantity > product.getStock()) {
            throw new RuntimeException("库存不足，无法更新");
        }

        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setProductId(productId);
        cart.setQuantity(quantity);

        int rows = cartMapper.updateCartItem(cart);
        return rows > 0;
    }

    @Override
    public boolean updateSelected(Long userId, Long productId, Integer selected) throws RuntimeException {
        if (userId == null || productId == null || selected == null) {
            throw new RuntimeException("参数错误，请检查");
        }

        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setProductId(productId);
        cart.setSelected(selected);

        int rows = cartMapper.updateCartItem(cart);
        return rows > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCartItem(Long userId, Long productId) throws RuntimeException {
        if (userId == null || productId == null) {
            throw new RuntimeException("参数错误，请检查");
        }

        Cart cartItem = cartMapper.getCartItemByUserAndProduct(userId, productId);
        if (cartItem == null) {
            throw new RuntimeException("购物车项不存在");
        }

        int rows = cartMapper.deleteCartItem(cartItem.getId());
        return rows > 0;
    }

    @Override
    public Cart getCartItem(Long userId, Long productId) {
        return cartMapper.getCartItemByUserAndProduct(userId, productId);
    }

    @Override
    public List<Cart> listCartItems(Long userId) {
        return cartMapper.listCartItemsByUser(userId);
    }

    @Override
    public boolean checkProductInCart(Long userId, Long productId) {
        Cart cartItem = cartMapper.getCartItemByUserAndProduct(userId, productId);
        return cartItem != null;
    }

    @Override
    public Long calculateSelectedTotal(Long userId) {
        List<Cart> cartItems = cartMapper.listCartItemsByUser(userId);
        if (cartItems == null || cartItems.isEmpty()) {
            return 0L;
        }
        BigDecimal total = BigDecimal.ZERO;
        for (Cart item : cartItems) {
            if (item.getSelected() == 1) {
                total = total.add(item.getProductPrice().multiply(BigDecimal.valueOf(item.getQuantity())));
            }
        }
        return total.longValue();
    }

    }
